Skip to main content

Best Time to Buy and Sell Stock

LeetCode 121 | Difficulty: Easy​

Easy

Problem Description​

You are given an array prices where prices[i] is the price of a given stock on the i^th day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

- `1 <= prices.length <= 10^5`

- `0 <= prices[i] <= 10^4`

Topics: Array, Dynamic Programming


Approach​

Dynamic Programming​

Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.

When to use

Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).


Solutions​

Solution 1: C# (Best: 112 ms)​

MetricValue
Runtime112 ms
Memory23.1 MB
Date2019-02-20
Solution
public class Solution {
public int MaxProfit(int[] prices) {
if(prices.Length==0) return 0;
int minSoFar = prices[0];
int maxProfitSoFar = 0;

for (int i = 1; i < prices.Length; i++)
{
maxProfitSoFar = Math.Max(maxProfitSoFar, prices[i] - minSoFar);
minSoFar = Math.Min(prices[i], minSoFar);

}

return maxProfitSoFar;
}
}
πŸ“œ 2 more C# submission(s)

Submission (2019-02-20) β€” 180 ms, 26 MB​

public class Solution {
public int MaxProfit(int[] prices) {
if(prices.Length==0) return 0;
int minSoFar = prices[0];
int maxProfitSoFar = 0;

for (int i = 1; i < prices.Length; i++)
{
maxProfitSoFar = Math.Max(maxProfitSoFar, prices[i] - minSoFar);
minSoFar = Math.Min(prices[i], minSoFar);
Console.WriteLine($"{prices[i]} {maxProfitSoFar} {minSoFar}");
}

return maxProfitSoFar<0 ? 0 : maxProfitSoFar;
}
}

Submission (2022-02-16) β€” 220 ms, 48.1 MB​

public class Solution {
public int MaxProfit(int[] prices) {
if(prices.Length==0) return 0;
int minSoFar = prices[0];
int maxProfitSoFar = 0;

for (int i = 1; i < prices.Length; i++)
{
maxProfitSoFar = Math.Max(maxProfitSoFar, prices[i] - minSoFar);
minSoFar = Math.Min(prices[i], minSoFar);

}

return maxProfitSoFar;
}
}

Complexity Analysis​

ApproachTimeSpace
Dynamic Programming$O(n)$$O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
  • Consider if you can reduce space by only keeping the last row/few values.